<?php
namespace app\wxwork\controller;

use think\Request;
use think\Db;
use think\facade\Session;
use tp5_lib\user\model\UserModel;
use tp5_lib\wxwork\logic\WXWork;
use tp5_lib\user_outside\logic\UserOutsideLogic;
use tp5_lib\user\extension\OutsideController;
use tp5_lib\wxwork\model\WxworkUserModel;

/**
 * 企业微信提供了OAuth的扫码登录授权方式
 * 目前支持authorization_code模式
 */
class IndexController extends OutsideController
{
    public function __get($name)
    {
        if($name === "outside"){
            if(empty($this->_outside)){
                $this->_outside=new WxworkUserModel();
            }
            return $this->_outside;
        }
        return parent::__get($name);
    }
    /**
     * 重定向到企业微信的页面，显示登录二维码
     */
    public function index()
    {
        $wxwork=new WXWork();
        $url="https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=".$wxwork->corpID
            ."&agentid=".$wxwork->agentID
            ."&redirect_uri=".urlencode($this->redirect_uri)
            ."&state=".urlencode("2333");
        $this->redirect($url);
    }
    /**
     * 在企业微信内置的浏览器中打开，直接进行授权
     */
    public function client()
    {
        $scope="snsapi_userinfo";
        $wxwork=new WXWork();
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$wxwork->corpID
            ."&agentid=".$wxwork->agentID
            ."&redirect_uri=".urlencode($this->redirect_uri)
            ."&state=".urlencode("2333")
            ."&response_type=code&scope=$scope#wechat_redirect";
        $this->redirect($url);
    }
    public $redirect_uri="http://tp5.1620428040.xyz/wxwork/index/receivecode";
    //在当前页面上显示登录二维码
    public function authWithEmbedQRCode()
    {
        $dom_id="wx-qr";
        $callback=Request::instance()->domain().url("callback");
        $wxwork=new WXWork();
        $params=[
            "id" => $dom_id,
            "appid" => $wxwork->corpID,
            "agentid" => $wxwork->agentID,
            "redirect_uri" => $callback ,
            "state" => "2333",
            // "href" => "",//引用样式的链接
        ];
        $html="<div id='$dom_id'></div>";
        $html.='<script src="http://rescdn.qqmail.com/node/ww/wwopenmng/js/sso/wwLogin-1.0.0.js"></script>';
        $html.='<script>window.WwLogin('.json_encode($params).');</script>';
        return $html;
    }
    /**
     * 接收code页面
     * 为了防止微信重复发送code造成的bug，这里添加一次额外的跳转
     */
    public function receiveCode()
    {
        $this->redirect("updateInfo",input());
    }
    /**
     * 实际接收code的页面
     * 更新用户信息并判断是否绑定
     */
    public function updateInfo()
    {
        $state=input("state");
        $code=input("code");

        $wxwork=new WXWork();
        $url="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$wxwork->getToken()."&code=".$code;
        /**
         * 此接口只能获取用户的ID
         * 当用户是企业成员时
         * {"errcode":0,"errmsg":"ok","UserId":"GuoDong","DeviceId":""}
         * 可以通过获取成员接口获取
         * 
         * 当用户不是企业成员时
         * {"errcode": 0,"errmsg": "ok","OpenId":"OPENID"}
         * 可以通过user_ticket获取
         */
        $info=$wxwork->get($url);
        if(!$info){
            $this->error("验证码已失效",url("user/login/login"));
        }
        if(isset($info["user_ticket"])){
            $url="https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=".$wxwork->getToken();
            $detail=$wxwork->post($url,["user_ticket"=>$info["user_ticket"]]);
        }
        else{
            $url="https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=".$wxwork->getToken()."&userid=".$info["UserId"];
            /** @see https://work.weixin.qq.com/api/doc#90000/90135/90196 */
            $detail=$wxwork->post($url,[]);
        }

        $outside=new WxworkUserModel();
        $record=$outside->db()->where(["userid"=>$detail["userid"]])->order("id","desc")->find();
        $detail["update_time"]=time();
        if($record){
            $outside->db()->where(["id"=>$record["id"]])->strict(false)->update($detail);
            if($record["user_id"]){
                $user=$this->logic->doLogin($record["user_id"]);
                $this->loginRedirect($user);
            }
            else{
                $this->redirect("bindAccount",["id"=>$record["id"]]);
            }   
        }
        else{
            $detail["create_time"]=time();
            $id=$outside->db()->strict(false)->insertGetId($detail);
            $this->redirect("bindAccount",["id"=>$id]);
        }
    }
    protected function convertUserInfo($data)
    {
        $user=[
            "username"=>"wechat_".$data["userid"],
            "mobile"=>$data["mobile"],
            "email"=>$data["email"],
            "nickname"=>$data["name"],
            "avatar"=>$data["avatar"],
            "signature"=>"",
            "sex"=>$data["gender"],
            "birthday"=>"",
            "url"=>"",
        ];
        return $user;
    }
}
